<?php
/* 
 * Upload script
 * Place this script on the podcast producer server (/Library/Webserver/Documents/upload.php)
 * And set podcast:podcast_path2uploadscript to your server location.
 */
$path = "/Users/moodle/tmp/";

//On récupère le secret partagé dans le fichier.
$fichierLocal = fopen($path.'secretpartage', 'r');
$cle = fread ($fichierLocal, filesize ($path.'secretpartage'));
fclose ($fichierLocal);

$transaction_signature = md5($_POST['username'] . $cle);
$ok = false;

if ($_POST['signature']  === $transaction_signature) {
    //La requète n'est pas forgée, on peut y aller:

    foreach($_FILES as $fieldName => $file){
        if($file['error'] == 0){
            if($reason = move_uploaded_file($file['tmp_name'],  $path.$_POST['username'].'_'.$file['name'])){
                $ok = true;
                //On renvoie le nom du fichier créé
                $name = $_POST['username'].'_'.$file['name'];
            }else{
                $reason = "Wrong path or wrong permission on it.";
            }
        }else{
        $reason = "Upload failed, bad server configuration";
        }
    }
}else{
    $reason = "Signature Failure";
}

$success = ($ok) ? 'SUCCESS' : 'FAILURE';

header('Content-Type: text/xml; charset=UTF-8');
$doc = new DOMDocument('1.0', 'utf-8');
$doc->preserveWhiteSpace = false;
$message = $doc->createElement( "message" );
$doc->appendChild( $message );
$successXml = $doc->createElement( "success" );
$reasonXml = $doc->createElement( "reason" );
$filename = $doc->createElement( "filename" );
$successXml->appendChild( $doc->createTextNode( $success ));
$reasonXml->appendChild( $doc->createTextNode( $reason ));
$filename->appendChild( $doc->createTextNode( $name ));
$message->appendChild( $successXml );
$message->appendChild( $reasonXml );
$message->appendChild( $filename );
$doc->formatOutput = true;
echo $doc->saveXML();
?>
